package com.tinyseed.emcp.api.app.common;

import cn.hutool.core.util.ReflectUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;

import java.util.ArrayList;
import java.util.List;

/**
 * 版权所有 © Copyright 2019<br>
 *
 * @Description: <br>
 * @CreateDate: Created in 2019/11/11 18:28 <br>
 * @Author: Simon.Yu
 * @Modify:
 */
public class ListUtil {

    /**
     * 复杂数组，变换数组里的类型
     *
     * @param fromList
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> List<T> copy(List fromList, Class<T> tClass) {
        List<T> toList = new ArrayList<>();
        fromList.forEach(temp -> {
            T item = ReflectUtil.newInstance(tClass);
            BeanUtils.copyProperties(temp, item);
            toList.add(item);
        });
        return toList;
    }

    /**
     * 复杂数组，变换数组里的类型
     *
     * @param fromPage
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> List<T> copy(Page fromPage, Class<T> tClass) {
        List<T> toList = new ArrayList<>();
        fromPage.forEach(temp -> {
            T item = ReflectUtil.newInstance(tClass);
            BeanUtils.copyProperties(item, temp);
            toList.add(item);
        });
        return toList;
    }

    /**
     * 复杂数组，变换数组里的类型
     *
     * @param fromPage
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> Page<T> copyPage(Page fromPage, Class<T> tClass) {
        List<T> toList = new ArrayList<>();
        fromPage.forEach(temp -> {
            T item = ReflectUtil.newInstance(tClass);
            BeanUtils.copyProperties(temp, item);
            toList.add(item);
        });
        PageImpl newPage = new PageImpl(toList, fromPage.getPageable(), fromPage.getTotalElements());
        return newPage;
    }

    public static <T> Page<T> buildPage(Page fromPage, List toList) {
        PageImpl newPage = new PageImpl(toList, fromPage.getPageable(), fromPage.getTotalElements());
        return newPage;
    }
}
